Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
"Cannot read properties of null (reading 'role')"

Code

this is my code in VS code to check if the user is an admin or a user

exports.authorizeRoles = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(
        new ErrorHandler(
          `Role: ${req.user.role} is not allowed to access this resource`,
          403
        )
      );
    }

    next();
  };
};

Error in postman API

the used declaration should be fine i don't know what's this problem

"success": false,
"message": "Cannot read properties of null (reading 'role')"
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Based on your description, I assume your user object on req.user is null, therefor it tries reading the property role of a null object.

Now, you can just check for null before validating the role, this way the API will at least return the correct error. (e.g. see here)

Something along the lines of (haven't tested the code):

if (null == req?.user?.role) {
    return next(new ErrorHandler(`Bad request`, 400));
}

But that still doesn't solve the issue for a valid request. For that I suggest you give us some more information on how you declare the request.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda